// pages/onlineOrdering/index.js
const app = getApp()
const req=require('../../utils/req')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navBarHeight:0,
    menuHeight:0,
    // 购物车动画
    animationData: {},
    animationMask: {},
    maskVisual: "hidden",
    // 购物车弹窗
    maskFlag: true,
    // 左侧导航数据
    tabs: [],
    // 分类商品数据
    tabsList: [],
    top: [],
    //被点击的左侧菜单
    indexId: 0,
    winHeight:'',
    toTitle:"title-0",
    scrollTop:0,
    keyword:'',
    totalPrice: 0, //选中商品总价格
    isCart:false,
    checked: false,
    isPopup:false,
    selectIndex:-1, //规格选择
    typeid:'',//选着规格绑定商品id,
    id:1,//扫码进入店铺id
    specificationsList:[], //规格弹窗数组
    deskName:'1',
    storeId:'',
    category:[],//分类
    productList:[], //商品列表
    selectedLeftMenuItem: "", // 选中分类
    toView:"", //商品显示位置
    cattoView:"",
    catscrollTop:0,
    catIndex:0,
    player:0,
    carts:[],
    proIndex:null,
    attrIndex:0,
    totalNum:0,
    totalPrice:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    if(options.scene){
      /*
      this.setData({
        id:decodeURIComponent(options.scene).split('=')[1]
      })
      */
      options.id=decodeURIComponent(options.scene).split('=')[1]
      
    }else{
      options.id=options.deskId
    }
    this.setData({
      id:options.id
    })
    this.getStoreId()
    const systemInfo = wx.getSystemInfoSync();
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    this.setData({
      navBarHeight:systemInfo.statusBarHeight + 44,
      menuHeight:menuButtonInfo.height
    })
    var that = this;
        wx.showLoading({
            mask: true,
            title: '加载中…',
        })
        // 关闭加载效果
        wx.hideLoading();
        //设置高度，左右滚动
        wx.getSystemInfo({
            success: function (res) {
                that.setData({
                    winHeight: res.windowHeight-133
                });
                var top2 = new Array();
                for (var i = 0; i < that.data.tabs.length; i++) {
                    wx.createSelectorQuery().select('#view-' + that.data.tabs[i].id).boundingClientRect(function (rect) {
                        var isTop = Number(rect.top);
                        top2.push(isTop);
                    }).exec();
                }
                that.setData({
                    top: top2
                });
            }
        });
        this.getDesk()
        /*
        this.getCategory().then(res=>{
          this.getProductList()
        })
        */
  },
  // 根据桌子获取商家id
  getStoreId(){
    let data = {
      id:this.data.id
    }
    app.agriknow.getStoreId(data).then(res=>{
      this.storeTypeList(res.data)
    })
  },
  // 获取菜单类型列表
  storeTypeList(id){
    let data = {
      id:id
    }
    app.agriknow.storeTypeList(data).then(res=>{
      this.setData({
        tabs:res.data,
        storeId:id
      })
      this.foodList()
    })
  },
  // 菜单列表
  foodList(){
    let tabsList = this.data.tabsList
    let data = {
      keyword:this.data.keyword,
      deskId:this.data.id
    }
    app.agriknow.foodList(data).then(res=>{
      tabsList = res.data
      tabsList.forEach((item,index)=>{
        item.quantity=0,
        item.checked=false
      })
      this.setData({
        tabsList:tabsList
      })
    })
  },
  // 搜索菜品
  bindReplaceInput(e){
    this.setData({
      keyword:e.detail.value
    })
    this.debounce()
  },
  debounce() {
    this.foodList()
  },
  // 左侧点击事件
  jumpIndex(e) {
    // 索引
    let index = e.currentTarget.dataset.menuindex;
    // 商品分类id
    let id = e.currentTarget.dataset.id;
    this.setData({
        indexId: index,
        // 商品分类名称 绑定点击左侧导航显示右侧商品信息
        toTitle: "title-" + id
    });
    console.log(this.data.toTitle)
  },
  // 右侧内容滑动就会触发
  scrollToLeft(res) {
    this.setData({
        scrollTop: res.detail.scrollTop
    });
    let length = this.data.top
    length.forEach((item,index)=>{
      if(length[index+1]>res.detail.scrollTop&&res.detail.scrollTop>=length[index]){
        this.setData({
          indexId:index
        })
      }
    })
  },
  // 购物车增加数量
  addCart: function (e) {
    let id = e.currentTarget.dataset.id
    let tabsList = this.data.tabsList
    tabsList.forEach(item => {
      if(item.id == id){
        item.quantity ++
      }
    });
    this.setData({
      tabsList:tabsList
    })
    this.updata()
  },
  //规格加入购物车
  popupAddCart(){
    if(this.data.selectIndex==-1) return this.tipsMessage('请选择规格')
    let id = this.data.typeid
    let tabsList = this.data.tabsList
    let index = this.data.selectIndex
    let specifications = this.data.specificationsList.specifications[index]
    tabsList.forEach(item => {
      if(item.id == id){
        item.quantity ++
        item.selectSpecifications = specifications
      }
    });
    this.setData({
      tabsList:tabsList,
      isPopup:false,
      selectIndex:-1
    })
    console.log(this.data.tabsList)
    this.updata()
  },
  // 购物车减少数量
  delCart: function (e) {
    let id = e.currentTarget.dataset.id
    let tabsList = this.data.tabsList
    tabsList.forEach(item => {
      if(item.id == id){
        item.quantity --
      }
    });
    this.setData({
      tabsList:tabsList
    })
    this.updata()
  },
  // 购物车单商品选择
  cartChange(e){
    let id = e.currentTarget.dataset.id
    let tabsList = this.data.tabsList
    let isChecked = true
    tabsList.forEach((item,index)=>{
      if(item.id==id){
        if(item.checked==false){
          item.checked=true
        }else{
          item.checked=false
        }
      }
    })
    // 是否全选
    tabsList.forEach((item,index)=>{
      if(item.checked==false&&item.quantity>0){
        isChecked=false
      }
    })
    this.setData({
      tabsList:tabsList,
      checked:isChecked
    })
  },
  // 全选按钮
  onChange(event) {
    let tabsList = this.data.tabsList
    tabsList.forEach(item=>{
      item.checked=event.detail
    })
    this.setData({
      tabsList:tabsList,
      checked:event.detail
    })
  },

  // 购物车数据更新
  updata(){
    this.getTotalPrice()
    this.showCart()
  },
  // 获取购物车总价、总数
  getTotalPrice: function () {
    let totalPrice = 0
    let tabsList = this.data.tabsList
    tabsList.forEach(item=>{
      if(item.quantity==0){
        item.checked = false
      }else{
        totalPrice+=Number((item.price*item.quantity).toFixed(2))
      }
    })
    this.setData({
      totalPrice:totalPrice,
      tabsList:tabsList
    })
  },
  // 购物车是否有商品
  showCart(){
    let isCart = false
    this.data.tabsList.forEach(item=>{
      if(item.quantity>0){
        isCart=true
      }
    })
    this.setData({
      isCart:isCart
    })
  },
  // 清空购物车
  cleanList: function (e) {
    let that = this
    let tabsList = that.data.tabsList
    wx.showModal({
      title: '提示',
      content: '是否确认删除购物车商品',
      success (res) {
        if (res.confirm) {
          tabsList.forEach((item,index)=>{
            if(item.checked==true){
              item.quantity = 0
              item.checked = false
            }
          })
          that.setData({
            tabsList:tabsList,
            checked:false
          })
          that.showCart()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    
  },
  //切换购物车开与关
  cascadeToggle: function () {
    var that = this;
    console.log(this.data.maskVisual)
    if (that.data.maskVisual == "hidden") {
      that.cascadePopup()
    } else {
      that.cascadeDismiss()
    }
  },
  // 打开购物车方法
  cascadePopup: function () {
    var that = this;
    // 购物车打开动画
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-in-out',
      delay: 0
    });
    that.animation = animation;
    animation.translate(0, -344).step();
    that.setData({
      animationData: that.animation.export(),
    });
    // 遮罩渐变动画
    var animationMask = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear',
    });
    that.animationMask = animationMask;
    animationMask.opacity(0.8).step();
    that.setData({
      animationMask: that.animationMask.export(),
      maskVisual: "show",
      maskFlag: false,
    });
  },

  // 关闭购物车
  cascadeDismiss: function () {
    var that = this
    // 购物车关闭动画
    that.animation.translate(0, 285).step();
    that.setData({
      animationData: that.animation.export()
    });
    // 遮罩渐变动画
    that.animationMask.opacity(0).step();
    that.setData({
      animationMask: that.animationMask.export(),
    });
    // 隐藏遮罩层
    that.setData({
      maskVisual: "hidden",
      maskFlag: true
    });
  },
  openPopup(e){
    let specificationsList = {}
    this.data.tabsList.forEach(item => {
      if(item.id == e.currentTarget.dataset.id){
        specificationsList = {
          specifications:item.specifications.split(','),
          price:item.price
        }
      }
    });
    this.setData({
      isPopup:true,
      typeid:e.currentTarget.dataset.id,
      specificationsList:specificationsList
    })
  },

  //规格选择
  onSelect(e){
    this.setData({
      selectIndex:e.currentTarget.dataset.index
    })
  },
  //规格弹窗关闭
  onClose(){
    this.setData({
      isPopup:false,
      selectIndex:-1
    })
  },
  // 去结算
  gotoOrder(){
    console.log(this.data.tabsList)
    // 获取数量
    let remake = 0
    // 规格字段
    let proList = []
    let tabsList = this.data.tabsList
    let isOrder = false
    tabsList.forEach(item=>{
      if(item.quantity>0){
        remake+=Number(item.quantity)
        proList.push({
          num:item.quantity,
          productId:item.id,
          specifications:item.selectSpecifications
        })
        isOrder = true
      }
    })
    if(!isOrder) return this.tipsMessage('请选择商品')
    let data = {
      price:this.data.totalPrice,
      storeId:this.data.storeId,
      type:2,
      remake:remake,
      proList:proList,
      // 线上核销
      num:0,
      packageId:0,
      userId:wx.getStorageSync('userLogin').userId,
      deskId:this.data.id
    }
    app.agriknow.userBuy(data).then(res=>{
      console.log(res)
      let id = res.data
      wx.navigateTo({
        url: '/pages/submitDetail/index?id='+id+'&type=2',
        success:function(res){
         // res.eventChannel.emit('submitDetail', {id:id,type:2})
        }
      })
    })
    
  },
  //提示信息
  tipsMessage(text) {
    wx.showToast({
      title: text,
      icon: 'none',
      duration: 2000,
      mask: true
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  getDesk:function(){
    var that=this
    var data={};
    data.deskId=this.data.id
    req.request('/ht/user/getDeskFoodList', data,'POST').then(res => {
      console.log(res.data)
      var datas=res.data
      var category=datas.productType
      var productList=datas.foodListRes
      var storeData=datas.storeData
      //storeData.storeBanner=storeData.storeBanner.split(',')
      storeData.deskImage=storeData.deskImage.split(',')
      that.setData({
        category:category,
        productList:productList,
        deskName:datas.deskName,
        storeData:storeData
      })

      productList.map(item => {
        // 添加节点的布局位置的查询请求
        wx.createSelectorQuery().select('#productItem' + item.typeId).boundingClientRect(rect => {
          console.log(rect)
          item.offsetTop = rect.top;
          item.height = rect.height;
        }).exec()
        item.num=0
        var specifications=item.specifications.split(',')
        var jsonArr=[]
        specifications.map(ite=>{
          var jsonStr={
            name:ite,
            num:0
          }
          jsonArr.push(jsonStr)
        })
   
        item.specifications=jsonArr
      })

      category.map(item => {
        // 添加节点的布局位置的查询请求
        wx.createSelectorQuery().select('#catItem' + item.id).boundingClientRect(rect => {
          console.log(rect)
          item.offsetTop = rect.top;
          item.height = rect.height;
        }).exec()
        
      })
      that.setData({
        productList: productList,
        category:category,
        selectedLeftMenuItem: category[0].id,
        cattoView:'catItem' + category[0].id,
        toView:'productItem' + category[0].id,
        catIndex:0,
      })

     
    })
  },


  // 左侧菜单栏切换事件
  bindCategory: function(e) {
    var id = e.currentTarget.dataset.id;
    var index=e.currentTarget.dataset.index
    this.setData({
      catIndex:index,
      selectedLeftMenuItem: id,
      toView: 'productItem' + id //不能数字开头，所以开头加了productItem
    });
  },
  // 监听右边商品列表滑动
  scrollProductList(e){
   console.log(e)
    var that=this
    var productList=this.data.productList
    var category=this.data.category
    productList.forEach(item => {
      console.log(e.detail.scrollTop,item.offsetTop)
     var catIndex=category.findIndex(ite=>{return ite.id==item.typeId})

      if (e.detail.scrollTop >= (item.offsetTop - productList[0].offsetTop) && e.detail.scrollTop <= (item.offsetTop - productList[0].offsetTop  + item.height)){
       // console.log('-----')
      
       
        that.setData({
          selectedLeftMenuItem: parseInt(item.typeId),
          catIndex:catIndex,
         cattoView:'catItem'+category[catIndex].id
        })
       
      
        

        
      }else{
        console.log('---++++++--')
     
      }
     
     
    })
  },

  //关闭弹窗
  close:function(){
    this.setData({
      player:0,
      attrIndex:0,
    })
  },
  //打开规格弹窗
  chooseAttr:function(e){
    var userInfo=wx.getStorageSync('userInfo')
    if(!userInfo.mobile){
      wx.navigateTo({
        url: '/pages/login/index',
      })
      return false
    }
    var index=e.currentTarget.dataset.index
    this.setData({
      proIndex:index,
      player:1
    })
  },
  //选择规格
  selectArr:function(e){
    var index=e.currentTarget.dataset.index
    this.setData({
      attrIndex:index
    })
  },
  addtoCart:function(){
   
    var proIndex=this.data.proIndex
    var attrIndex=this.data.attrIndex
    
    var key='productList['+proIndex+'].specifications['+attrIndex+'].num'
    console.log(key)
    this.setData({
        [key]:1
    })
    this.updateCart()
  },
  //减少
  reduce:function(e){
    var productlist=this.data.productList
    console.log(e)
    var aindex=e.currentTarget.dataset.aindex
    if(aindex>=0){
      this.setData({
        attrIndex:aindex
      })
    }
    var proIndex=e.currentTarget.dataset.index
    var attrIndex=this.data.attrIndex

    var num=productlist[proIndex].specifications[attrIndex].num
    num--
    if(num<0){
      num=0
    }
    var key='productList['+proIndex+'].specifications['+attrIndex+'].num'
    console.log(key)
    this.setData({
        [key]:num
    })
    this.updateCart()
  },
  //增加
  add:function(e){
    var userInfo=wx.getStorageSync('userInfo')
    if(!userInfo.mobile){
      wx.navigateTo({
        url: '/pages/login/index',
      })
      return false
    }
    var productlist=this.data.productList
    var aindex=e.currentTarget.dataset.aindex
    if(aindex>=0){
      this.setData({
        attrIndex:aindex
      })
    }
    var proIndex=e.currentTarget.dataset.index
    var attrIndex=this.data.attrIndex
    var num=productlist[proIndex].specifications[attrIndex].num
    var snum=productlist[proIndex].num
    var stockNum=productlist[proIndex].stockNum
    console.log(snum,stockNum)
    if(snum<stockNum){
      num++
    }else{
      wx.showToast({
        title: '库存不足',
        icon:'none',
        duration:1500
      })
      return false
    }
    
    
    var key='productList['+proIndex+'].specifications['+attrIndex+'].num'
    console.log(key)
    this.setData({
        [key]:num
    })
    this.updateCart()
  },

  //更新购物车
  updateCart:function(){
    var that=this
    var productList=this.data.productList
    var jsonArr=[]
    productList.map((item,index)=>{
      var nums=0
      item.specifications.map((ite,i)=>{
        if(ite.num>0){
          var jsonStr={
            name:item.name,
            productId:item.id,
            image:item.smallImage,
            price:Number(item.price*ite.num).toFixed(2),
            specifications:ite.name,
            num:ite.num,
            proIndex:index,
            attrIndex:i
          }
          nums += ite.num
          jsonArr.push(jsonStr)
        }
      })
      item.num=nums
    })
    var totalPrice=0
    var totalNum=0
    jsonArr.map(item=>{
      totalPrice += Number(item.price)
      totalNum += parseInt(item.num)
    })
    console.log(totalPrice,jsonArr,totalNum)
    this.setData({
      totalPrice:totalPrice,
      carts:jsonArr,
      totalNum:totalNum,
      productList:productList
    })
    if(jsonArr.length==0){
      if(that.data.player==2){
        that.setData({
          player:0,
          attrIndex:0
        })
      }
    }

  },
  //打开购物车
  openCart:function(){
    var player=this.data.player

    if(player==2){
  
      this.setData({
        player:0,
        attrIndex:0
      })
    }else{
      this.setData({
        player:2
      })
    }
   
  },
  //清空购物车
  clearCart:function(){
    var that=this
    wx.showModal({
      title: '温馨提示',
      content: '是否清空该购物车',
      success: function (res) {
        if (res.confirm) {
          var productList=that.data.productList
          productList.map(item=>{
            item.num=0
            var specifications=item.specifications
            specifications.map(ite=>{
              ite.num=0
            })
            item.specifications=specifications
          })
          that.updateCart()
          
         
        } else if (res.cancel) {
          console.log('取消')
        }
      }
    })
  },
  //提交订单
  createOrder:function(){
    var that=this
    var carts=this.data.carts
    if(carts.length==0){
      wx.showToast({
        title: '请先添加商品',
        icon:'none',
        duration:1500,
        mask:true
      })
      return false
    }
    var storeData=this.data.storeData
    var deskId=this.data.id
    var totalPrice=this.data.totalPrice

    var data={}
    data.type=2
    data.deskId=deskId
    data.storeId=storeData.storeId
    data.price=totalPrice
    data.proList=carts
    data.num=0
    data.packageId=0
    //data.remake=storeData.name
    req.request('/ht/user/userBuy',data,'POST').then(res=>{
      console.log(res)
      var id = res.data
      wx.navigateTo({
        url: '/pages/submitDetail/index?id='+id+'&type=2',
        success:function(res){
         // res.eventChannel.emit('submitDetail', {id:id,type:2})
         //下单后清除购物车
         var productList=that.data.productList
          productList.map(item=>{
            item.num=0
            var specifications=item.specifications
            specifications.map(ite=>{
              ite.num=0
            })
            item.specifications=specifications
          })
          that.updateCart()
        }
      })
    })

  },

  toSearch:function(){
    wx.navigateTo({
      url: '/pages/onlineOrdering/search',
    })
  },

  call:function(e){
    var mobile=e.currentTarget.dataset.mobile
    wx.makePhoneCall({
      phoneNumber: mobile,
    })
  }
  
  
})